package com.hdaccp.xingmu.controller;

import com.hdaccp.xingmu.dao.DanyuanDao;
import com.hdaccp.xingmu.entity.Danyuan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/danyuan")
public class DanyuanCon {
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private DanyuanDao danyuanDao;




    @RequestMapping("/danlist")
    @ResponseBody
    public List<Danyuan> dalist(){
        return danyuanDao.findAll();
    }

    /**
     * 查询
     * @return
     */
    @RequestMapping("/allq")
    @ResponseBody
    public Map<String,Object> All( int pageSize,int pageNumber){
        //分页
        String jpal = "from Danyuan where 1=1";

        Query qu = entityManager.createQuery(jpal);
        //起始页书
        qu.setFirstResult((pageNumber - 1) * pageSize);
        //结束页数
        qu.setMaxResults(pageSize);

        //查询多少条数据
        String jpa = "select count(s) from Danyuan s";

        Query q = entityManager.createQuery(jpa);

        Long count = (Long) q.getSingleResult();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", count);
        map.put("rows", qu.getResultList());
        return map;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/delq")
    @ResponseBody
    public  Map<String,Object> del(Long id){
        danyuanDao.deleteById(id);
        return All(4,1);
    }

    /**
     * 修改
     * @param danyuan
     * @return
     */
   @RequestMapping("/updqqqqq")
   @ResponseBody
    public  Map<String,Object> upd(Danyuan danyuan){
        danyuanDao.save(danyuan);
        return All(4,1);
   }

    /**
     * 添加
     * @param danyuan
     * @return
     */
   @RequestMapping("/addqqqq")
   @ResponseBody
    public Map<String,Object> add(Danyuan danyuan){
       danyuanDao.save(danyuan);
       return All(4,1);
   }
}
